<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <div class="filter-container">
      <el-input
        @keyup.enter.native="handleFilter"
        style="width: 200px"
        class="filter-item"
        placeholder="用户姓名"
        v-model="keyword"
      >
      </el-input>

      <!-- <el-select clearable class="filter-item" style="width: 130px" v-model="listQuery.type" placeholder="类型">
        <el-option v-for="item in  typeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key">
        </el-option>
      </el-select> -->

      <el-button
        class="filter-item"
        type="primary"
        v-waves
        icon="search"
        @click="handleFilter"
        >搜索</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        @click="handleCreate"
        icon="edit"
        >添加</el-button
      >

      <el-button
        class="filter-item"
        type="primary"
        @click="handleDelAll"
        icon="edit"
        >批量删除</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="document"
        @click="handleDownload"
        >导出</el-button
      >
    </div>

    <!-- 表格 -->
    <el-table
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      :data="users"
      border
      fit
      highlight-current-row
    >
      <el-table-column type="selection" width="40"> </el-table-column>

      <el-table-column align="center" label="序号" width="45">
        <template slot-scope="scope">
          {{ scope.$index }}
        </template>
      </el-table-column>

      <el-table-column label="姓名"  align="center" width="100">
        <template slot-scope="scope">
          {{ scope.row.user_name }}
        </template>
      </el-table-column>

      <el-table-column label="账号" align="center" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.user_account }}</span>
        </template>
      </el-table-column>

      <el-table-column label="密码" align="center" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.user_pwd }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="邮箱">
        <template slot-scope="scope">
          <!-- <i class="el-icon-time"></i> -->
          <span>{{ scope.row.user_email }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="头像" width="100">
        <template slot-scope="scope">
          <el-image :src="scope.row.user_cover" fit="contain"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" label="描述">
        <template slot-scope="scope">
          <span v-if="scope.row.user_desc">{{ scope.row.user_desc | simpleIntro}}</span>
        </template>
      </el-table-column>

       <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{ scope.row.ctime}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <!-- <i class="el-icon-time"></i> -->
          <span v-if="scope.row.user_state!=0">在线</span>
          <span v-else>离线</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div  class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.currPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>

export default {
  data() {
    return {
      // list: null,
      // listLoading: true,
      users: [],
      list: null, //表格list [].push({})
      total: null,
      listQuery: {
        currPage: 1,
        pageSize: 10,
      },
      temp: {
        chnlId: "",
        hisChnlId: "",
        chnlName: "",
        state: "",
        isavailable: "",
        orderNum: 10,
      },
      typeOptions: [
        { key: "001", display_name: "类型1" },
        { key: "002", display_name: "类型2" },
        { key: "003", display_name: "类型3" },
      ],
      dialogFormVisible: false,
      multipleSelection: [],
      keyword:''
    };
  },
  async created(){
    this.getList()
  },
  filters:{
    simpleIntro(intros){
      return intros.length>50?intros.substring(0,51)+'...':intros
    },
  },
  methods: {
    //获取列表数据
    async getList() {
      let res = await this.$http.get('/all_users',{params:{pageSize:this.listQuery.pageSize, currPage:this.listQuery.currPage}})
      this.users = res.data.users;
      this.listQuery.currPage = parseInt(res.data.currPage)
      this.listQuery.pageSize = parseInt(res.data.pageSize)
      this.total = res.data.total

    },
    //编辑
    handleEdit(index, row) {
      this.$store.commit('SET_USER', row)
      console.log("编辑的row：", index, "-----", row);
      //跳页面进行修改
      this.$router.push('/usersManage/userUpdate');
    },

    //单个删除
    handleDelete(index, row) {
      let vm = this;
      console.log("单个删除选择的row：", index, "-----", row);
      
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          vm.delFun(row);
          //前端删除。
           vm.users.splice(index,1)
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    //调取删除接口的删除方法
    delFun(row) {
      this.$http.delete('/delete_user',{params:{user_id: row.user_id}}).then(res=>{})
    },
    //批量删除
    handleDelAll() {
      let vm = this;
      console.log("批量删除选择的row：", vm.multipleSelection);

      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定批量删除",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //前端依次执行单个删除操作
           vm.users = vm.users.filter((item)=>{
              for(let selection of vm.multipleSelection){
                if(item.user_id === selection.user_id){
                  return false
                }
              }
              return true;
            })
          for (var index in vm.multipleSelection) {
              console.log('======',vm.multipleSelection[index])
              vm.delFun(vm.multipleSelection[index]);
          };
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    //搜索
    async handleFilter() {
      let res = await this.$http.get('/search_user',{params:{keyword:this.keyword, pageSize:this.listQuery.pageSize, currPage:this.listQuery.currPage}})
      this.users = res.data.users;
      this.listQuery.currPage = parseInt(res.data.currPage)
      this.listQuery.pageSize = parseInt(res.data.pageSize)
      this.total = res.data.total
      console.log(res.data);
    },
    //操作分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.getList();
    },
    //操作分页
    handleCurrentChange(val) {
      console.log("--------", val);
      this.listQuery.currPage = val;
      this.getList();
    },
    //新增
    handleCreate() {
      //跳到新增页面
      this.$router.push("/usersManage/userAdd");
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleDownload() {
      let vm = this;

      require.ensure([], () => {
        const { export_json_to_excel } = require("vendor/Export2Excel");
        const tHeader = ["ID", "昵称", "账号", "密码", "邮箱","描述","创建时间","头像地址"];
        const filterVal = [
          "user_id",
          "user_name",
          "user_account",
          "user_pwd",
          "user_email",
          "user_desc",
          "ctime",
          "user_cover"
        ];
        const list = vm.users;
        const data = vm.formatJson(filterVal, list);
        console.log(data);
        export_json_to_excel(tHeader, data, "用户表");
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
  },
};
</script>
